package com.kycxika.app;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.graphics.BitmapCompat;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.isseiaoki.simplecropview.CropImageView;
import com.isseiaoki.simplecropview.callback.CropCallback;
import com.isseiaoki.simplecropview.callback.LoadCallback;
import com.isseiaoki.simplecropview.callback.SaveCallback;
import com.kycxika.app.activity.base.BasePhotoActivity;
import com.kycxika.app.activity.pic.PhotoPickerActivity;
import com.kycxika.app.bean.pic.UpdateUserInfoConfig;
import com.kycxika.app.bean.pic.UpdateUserInfoEntity;
import com.kycxika.app.bean.pic.UploadPicEntiry;
import com.kycxika.app.dbutils.IntImp.KycXkIApi;
import com.kycxika.app.dbutils.inter.HttpQuestResultListener;
import com.kycxika.app.utils.Bitmaputil;
import com.kycxika.app.utils.FileUtil;
import com.kycxika.app.utils.RXUnit.RxBus;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import java.io.File;

import static com.kycxika.app.KycXikaApplication.context;

public class PicCutoutActivity extends BasePhotoActivity implements HttpQuestResultListener {

    private static final int REQUEST_PICK_IMAGE = 10011;
    private static final int REQUEST_SAF_PICK_IMAGE = 10012;
    private static final String PROGRESS_DIALOG = "ProgressDialog";
    private static final String TAG = PicCutoutActivity.class.getSimpleName();
    private CropImageView mCropView;
    private LinearLayout mRootLayout;
    private UpdateUserInfoEntity rxUpdateUserInfoEntity = new UpdateUserInfoEntity();
    private UpdateUserInfoConfig updateUserInfoConfig = UpdateUserInfoConfig.getInstance();
    private KycXkIApi xkIApi;
    private ProgressDialog dialogProgress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic_cutout);

        xkIApi = KycXkIApi.getInstance(this);
        xkIApi.setHttpQuestResultListener(this);
        initView();

        Intent intent = getIntent();
        String result = intent.getStringExtra(PhotoPickerActivity.SELECT_RESULTS);
        Uri sourceUri = FileUtil.getImageContentUri(context, new File(result));
        mCropView.setCropMode(CropImageView.CropMode.SQUARE);
        showProgress();
        mCropView.startLoad(sourceUri, mLoadCallback);
    }

    private void initView() {
        bindViews();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        //toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void bindViews() {
        mCropView = (CropImageView) findViewById(R.id.cropImageView);
        findViewById(R.id.buttonDone).setOnClickListener(btnListener);
        findViewById(R.id.buttonFitImage).setOnClickListener(btnListener);
        findViewById(R.id.button1_1).setOnClickListener(btnListener);
        findViewById(R.id.button3_4).setOnClickListener(btnListener);
        findViewById(R.id.button4_3).setOnClickListener(btnListener);
        findViewById(R.id.button9_16).setOnClickListener(btnListener);
        findViewById(R.id.button16_9).setOnClickListener(btnListener);
        findViewById(R.id.buttonFree).setOnClickListener(btnListener);
        findViewById(R.id.buttonPickImage).setOnClickListener(btnListener);
        findViewById(R.id.buttonRotateLeft).setOnClickListener(btnListener);
        findViewById(R.id.buttonRotateRight).setOnClickListener(btnListener);
        findViewById(R.id.buttonCustom).setOnClickListener(btnListener);
        findViewById(R.id.buttonCircle).setOnClickListener(btnListener);
        findViewById(R.id.buttonShowCircleButCropAsSquare).setOnClickListener(btnListener);
        mRootLayout = (LinearLayout) findViewById(R.id.layout_root);
    }

    private final View.OnClickListener btnListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.buttonDone:
                    showProgress();
                    mCropView.startCrop(createSaveUri(), mCropCallback, mSaveCallback);
                    break;
                case R.id.buttonFitImage:
                    mCropView.setCropMode(CropImageView.CropMode.FIT_IMAGE);
                    break;
                case R.id.button1_1:
                    mCropView.setCropMode(CropImageView.CropMode.SQUARE);
                    break;
                case R.id.button3_4:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_3_4);
                    break;
                case R.id.button4_3:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_4_3);
                    break;
                case R.id.button9_16:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_9_16);
                    break;
                case R.id.button16_9:
                    mCropView.setCropMode(CropImageView.CropMode.RATIO_16_9);
                    break;
                case R.id.buttonCustom:
                    mCropView.setCustomRatio(7, 5);
                    break;
                case R.id.buttonFree:
                    mCropView.setCropMode(CropImageView.CropMode.FREE);
                    break;
                case R.id.buttonCircle:
                    mCropView.setCropMode(CropImageView.CropMode.CIRCLE);
                    break;
                case R.id.buttonShowCircleButCropAsSquare:
                    mCropView.setCropMode(CropImageView.CropMode.CIRCLE_SQUARE);
                    break;
                case R.id.buttonRotateLeft:
                    mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_M90D);
                    break;
                case R.id.buttonRotateRight:
                    mCropView.rotateImage(CropImageView.RotateDegrees.ROTATE_90D);
                    break;
                case R.id.buttonPickImage:
                    // TODO: 16/8/20
                    choosePictrue();
                    break;
            }
        }
    };

    private void choosePictrue() {
        Intent intent = new Intent(context, PhotoPickerActivity.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean(PhotoPickerActivity.SELECT_RESULTS, true);
        intent.putExtras(bundle);
        startActivityForResult(intent, 1001);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.gc();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            String resultPhotoUri = data.getStringExtra(PhotoPickerActivity.SELECT_RESULTS);
            if (resultPhotoUri == null) {
                return;
            }
            Uri sourceUri = FileUtil.getImageContentUri(context, new File(resultPhotoUri));
            showProgress();
            mCropView.startLoad(sourceUri, mLoadCallback);


        }
    }

    public Uri createSaveUri() {
        File file = new File(context.getCacheDir(), "cropped" + System.currentTimeMillis());
        if (file.exists()) {
            file.delete();
        }
        return Uri.fromFile(file);
    }


    /*Callbacks*/
    private final LoadCallback mLoadCallback = new LoadCallback() {
        @Override
        public void onSuccess() {
            dismissProgress();
        }

        @Override
        public void onError() {
            dismissProgress();
        }
    };

    private final CropCallback mCropCallback = new CropCallback() {
        @Override
        public void onSuccess(Bitmap cropped) {
        }

        @Override
        public void onError() {
        }
    };

    private final SaveCallback mSaveCallback = new SaveCallback() {
        @Override
        public void onSuccess(Uri outputUri) {
            rxUpdateUserInfoEntity.setHeaderUri(outputUri);
            updateUserInfoConfig.setUserheaderurl(outputUri);
            final String urlpath = FileUtil.getRealFilePath(context, outputUri);
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    Bitmap picBitmap = Bitmaputil.getLocalBitmap(urlpath);
                    // 16/8/30 如果图片大于200k,则对file进行压缩到多少k. It's best to just use the support library:
                    int bitmapByteCount = BitmapCompat.getAllocationByteCount(picBitmap);
                    if (bitmapByteCount > 200 * 1024) {
                        Luban.with(context)
                                .load(new File(urlpath))                     //传人要压缩的图片
                                .setCompressListener(new OnCompressListener() { //设置回调

                                    @Override
                                    public void onStart() {
                                        //  压缩开始前调用，可以在方法内启动 loading UI
                                    }

                                    @Override
                                    public void onSuccess(File file) {
                                        //  压缩成功后调用，返回压缩后的图片文件
                                       // RxBus.getDefault().post(file.getAbsolutePath());
                                        //walltauser.uploadPictrue(file.getAbsolutePath());//or file.getPath()
                                        xkIApi.uploadPictrue(file.getAbsolutePath());

                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        //  当压缩过去出现问题时调用
                                        //walltauser.uploadPictrue(urlpath);
                                        xkIApi.uploadPictrue(urlpath);
                                    }
                                }).launch();    //启动压缩

                    }else {
                        //walltauser.uploadPictrue(urlpath);
                        xkIApi.uploadPictrue(urlpath);
                    }
                }
            });


        }

        @Override
        public void onError() {
            dismissProgress();
        }
    };

    public void showProgress() {
        dialogProgress = new ProgressDialog(this);
        dialogProgress.setMessage("正在操作,请稍后.....");
        //dialog1.setProgressStyle(R.drawable.progressbar_circle);
        dialogProgress.setIndeterminateDrawable(getResources().getDrawable(R.drawable.progressbar_circle));
        dialogProgress.setCanceledOnTouchOutside(false);
        dialogProgress.show();
    }

    public void dismissProgress() {
        dialogProgress.dismiss();
    }

    @Override
    public void onError(Object object) {
        dismissProgress();
        Toast.makeText(PicCutoutActivity.this,"服务连接出错.",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSuccess(Object object) {
        if (object instanceof UploadPicEntiry) {
            //得到crop picture path上传到服务器后成功的返回图片md5
            UploadPicEntiry uploadPicEntiry = (UploadPicEntiry) object;
            // List<UploadPicEntiry.Data> listdata = uploadPicEntiry.getData();
            Log.i("TAG","msg  ------ " +uploadPicEntiry.getMsg());
            UploadPicEntiry.DataBean dataBean = uploadPicEntiry.getData();
            Toast.makeText(PicCutoutActivity.this,uploadPicEntiry.getMsg(),Toast.LENGTH_SHORT).show();
            //xkIApi.saveUserHeaderUrl(dataBean.getSuccess());
            dismissProgress();
            finish();
            // if (listdata != null && listdata.size() > 0) {
            /*if(dataBean != null) {
                //String urlmd5path = listdata.get(0).getMd5();
                String userAvatorUrl = dataBean.getSuccess();//HttpApiConst.UploadImgBaseDomain + "/" + urlmd5path;
                rxUpdateUserInfoEntity.setHeadermd5serverpath(userAvatorUrl);
                final UpdateUserInfoBody updateUserInfoBody = new UpdateUserInfoBody();
                updateUserInfoBody.setPhone(xkIApi.getUserAcount());
                updateUserInfoBody.setImgurl(userAvatorUrl);
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        //walltauser.updateUserInfo(updateUserInfoBody, updateUserInfoConfig.getUserheaderurl());
                        //xkIApi.uploadPictrue();
                    }
                });


            } else {
                dismissProgress();
                //showDefaultSnackbar("操作失败");
                Toast.makeText(PicCutoutActivity.this,"操作失败",Toast.LENGTH_SHORT).show();
            }*/


        }

        if (object instanceof UpdateUserInfoEntity) {
            //更新个人信息成功(更新头像)
            UpdateUserInfoEntity update = (UpdateUserInfoEntity) object;
            int responseCode = update.getResponseCode();
            if (responseCode == 200) {
                //xkIApi.saveUserUpdatedAt(update.getUpdated_at());
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        RxBus.getDefault().post(rxUpdateUserInfoEntity);
                        //RxBus.getDefault().post(updateUserInfoConfig);
                        dismissProgress();
                        finish();

                    }
                });
            }
        }
    }

    @Override
    public void onQuestErroCode(Object object) {
        if (object instanceof UploadPicEntiry) {
            UploadPicEntiry uploadPicEntiry = (UploadPicEntiry) object;
            dismissProgress();
            Toast.makeText(PicCutoutActivity.this,uploadPicEntiry.getMsg(),Toast.LENGTH_SHORT).show();
        }
    }
}
